package com.yunsoft.notice.service.api.impl;
import com.alibaba.fastjson.JSON;
import com.fld.central.common.model.code.BaseCode;
import com.fld.central.common.model.exception.SpiException;
import com.fld.central.common.model.protocol.ResultDto;
import com.fld.platform.commons.utils.ThrowableUtils;
import com.yunsoft.notice.api.api.NotifyRpc;
import com.yunsoft.notice.api.dto.BaseMessage;
import com.yunsoft.notice.api.dto.NotifyRecordDto;
import com.yunsoft.notice.api.dto.sms.SmsMessage;
import com.yunsoft.notice.api.enums.SmsEnum;
import com.yunsoft.notice.service.db.entity.NotifyRecord;
import com.yunsoft.notice.service.db.enums.NotifyEnum;
import com.yunsoft.notice.service.manager.NotifyRecordManager;
import com.yunsoft.notice.service.manager.SmsManager;
import com.yunsoft.notice.service.manager.UniSmsManager;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * @author yangyunfeng
 * @description
 * @date AD 2023/10/25
 */
@Service
public class NotifyRpcImpl implements NotifyRpc {

  private final static Logger LOGGER = LoggerFactory.getLogger(NotifyRecordManager.class);

  @Autowired
  private SmsManager smsManager;

  @Autowired
  private NotifyRecordManager notifyRecordManager;

  @Override
  public ResultDto<List<NotifyRecordDto>> query(String requestId) {
    return null;
  }

  @Override
  public ResultDto<String> send(BaseMessage message) throws SpiException {
    if(message == null) {
      throw new SpiException(BaseCode.ERROR,"对象为空");
    }
    //sms
    if (message instanceof SmsMessage) {
      SmsMessage smsMessage = (SmsMessage) message;
      return send(smsMessage);
    }


    throw new SpiException(BaseCode.ERROR,"未知消息");
  }


  /**
   * 发送短信消息，目前只支持验证码/通知类短信
   * @param message
   * @return
   * @throws SpiException
   */
  private ResultDto<String> send(SmsMessage message) throws SpiException {
    if (message == null) {
      throw new SpiException(BaseCode.ERROR, "对象为空");
    }
    if (message.getType() == null) {
      throw new SpiException(BaseCode.ERROR, "短信类型为空");
    }
    if (StringUtils.isBlank(message.getContent())) {
      throw new SpiException(BaseCode.ERROR, "短信内容为空");
    }
    if (CollectionUtils.isEmpty(message.getPhones())) {
      throw new SpiException(BaseCode.ERROR, "手机号为空");
    }
    //
    String[] phones = new String[message.getPhones().size()];
    phones = message.getPhones().toArray(phones);
    //
    if (message.getType() == SmsEnum.NOTICE || message.getType() == SmsEnum.INTERNATION_CODE) {
      String requestId = UUID.randomUUID().toString().replaceAll("-", "");
      for (String phone : phones) {
        NotifyRecord record = createNotifyRecord(requestId, NotifyEnum.SMS, message.getService(), null, phone, "通知短信", message.getContent());
        try {
          String result = null;
          if (message.getType() == SmsEnum.NOTICE) {
            result = smsManager.publish(phone, message.getContent());
          } else {
            if (StringUtils.isBlank(message.getTemplateCode()) || StringUtils.isBlank(message.getSignName())) {
//              result = aliyunSmsManager.publish(phone,signName,templateCode, message.getContent());
            } else {
//              result = aliyunSmsManager.publish(phone,message.getSignName(),message.getTemplateCode(), message.getContent());
            }
          }
          updateRecord(record, 1, result);
        } catch (Exception e) {
          updateRecord(record, 2, ThrowableUtils.throwableToString(e));
          LOGGER.error("[发送通知短信异常], result={}。", record.getResult());
        } finally {
          //保存
          notifyRecordManager.asyncSave(record);
        }
      }
      return new ResultDto<>(BaseCode.OK, "成功", requestId);
    }  else {
      NotifyRecord record = createNotifyRecord(NotifyEnum.SMS, message.getService(), null, JSON.toJSONString(phones), "营销短信", message.getContent());
      try {
        String result = smsManager.publish(message.getPhones(), message.getContent());
        updateRecord(record, 1, result);
        return new ResultDto<String>(BaseCode.OK, "成功", record.getRequestId());
      } catch (Exception e) {
        updateRecord(record, 2, ThrowableUtils.throwableToString(e));
        throw new SpiException(BaseCode.ERROR, record.getResult());
      } finally {
        //保存
        notifyRecordManager.asyncSave(record);
      }
    }
  }

  private NotifyRecord createNotifyRecord(NotifyEnum type,String service,String sender,String receiver,String title,String content) {
    NotifyRecord record = new NotifyRecord();
    record.setRequestId(UUID.randomUUID().toString().replaceAll("-",""));
    record.setService(service);
    record.setType(type);
    record.setSender(sender);
    record.setReceiver(receiver);
    record.setTitle(title);
    record.setContent(content);
    record.setCreateDate(new Date());
    record.setUpdateDate(new Date());
    record.setStatus(0);
    record.setResult("");
    return record;
  }
  private NotifyRecord createNotifyRecord(String requestId,NotifyEnum type,String service,String sender,String receiver,String title,String content) {
    NotifyRecord record = new NotifyRecord();
    record.setRequestId(requestId);
    record.setService(service);
    record.setType(type);
    record.setSender(sender);
    record.setReceiver(receiver);
    record.setTitle(title);
    record.setContent(content);
    record.setCreateDate(new Date());
    record.setUpdateDate(new Date());
    record.setStatus(0);
    record.setResult("");
    return record;
  }

  private void updateRecord(NotifyRecord record,int status,String result) {
    record.setStatus(status);
    record.setResult(result);
    record.setUpdateDate(new Date());
  }

}
